package com.ceba.test.modules.usermanage.dao;

import com.ceba.test.base.configs.CebaConfig;
import com.ceba.base.web.dao.IBaseDao;

import abc.data.DataTable;
import abc.data.Sql;
import abc.data.SqlSessionManager;
import abc.data.store.IStore;
import abc.data.store.StoreManager;
import abc.object.IObject;
import abc.object.XObject;

public class LoginDao extends IBaseDao {
	
	/**
	 * 登录
	 */
	
	public DataTable login(String loginID) throws Exception{
		Sql sql = new Sql("SELECT U_USER.ID,U_USER.NAME,u_privilege.OBJECT_ID AS ROLE,"
				+ " U_USER.PASSWORD,u_role.LOGIN_INDEX,u_role.LOGIN_INDEX_SIGNVER,"
				+ " u_role.LOGIN_INDEX_SIGNONLY,"
				+ " u_user.department_ID,u_department.Step "
				+ " FROM U_USER "
				+ " LEFT OUTER JOIN u_privilege ON u_privilege.USER_ID=U_USER.ID AND u_privilege.FLAG='1'"
				+ " LEFT OUTER JOIN u_role ON u_privilege.OBJECT_ID=u_role.ID"
				+ " LEFT OUTER JOIN u_department ON u_department.ID = u_user.department_ID"
				+ " WHERE U_USER.LOGIN_ID=?");
		sql.addParameter("LOGIN_ID", loginID);
		DataTable dt = SqlSessionManager.getDataTable(sql);// DBManager.existRecord("u_user", "LOGIN_ID='"+loginID+"' AND PASSWORD='"+psw+"'"
		return dt;
	}
		
	
	
	
	public DataTable moblieLoginDao(String loginID) throws Exception{
		Sql sql = new Sql("SELECT U_USER.ID,U_USER.NAME,u_privilege.OBJECT_ID AS ROLE,U_USER.PASSWORD,u_role.LOGIN_INDEX "
				+ "FROM U_USER "
				+ " LEFT OUTER JOIN u_privilege ON u_privilege.USER_ID=U_USER.ID AND u_privilege.FLAG='1'"
				+ " LEFT OUTER JOIN u_role ON u_privilege.OBJECT_ID=u_role.ID"
				+ " WHERE U_USER.LOGIN_ID=?");
		sql.addParameter("LOGIN_ID", loginID);
		DataTable dt = SqlSessionManager.getDataTable(sql);// DBManager.existRecord("u_user", "LOGIN_ID='"+loginID+"' AND PASSWORD='"+psw+"'")
		return dt;
	}
	
	/**
	 * 保存密码
	 * @param pw
	 * @param userId
	 * @return
	 */
	public Boolean savePassword(String pw,String userId){
		pw=CebaConfig.getEncode(pw);//Config.UKEY + BASE64.encode(pw);
		IStore store = StoreManager.create("u_user");
		IObject object = new XObject("u_user");
		object.put("ID",userId);
		object.put("Password",pw);
		long l=store.update(object);
		if(l>0){
			return true;
		}
		return false;
	}
	
	/**
	 * 获取department的某个字段值
	 * @param userId
	 * @param field
	 */
	public String getUserDepartmentFieldValueByUserId(String userId,String field){
		Sql sql=new Sql("SELECT u_department."+field+" FROM u_user LEFT OUTER JOIN "
				+ " u_department ON u_department.ID=u_user.Department_ID WHERE u_user.ID=?");
		sql.addParameter(userId);
		return SqlSessionManager.getFieldStringValue(sql);
	}
	
	/**
	 * 根据查询条件获取部门
	 * @param condition
	 * @return
	 */
	public DataTable getDepartmentsByCondition(String condition){
		Sql sql=new Sql("SELECT ID FROM u_department WHERE STEP LIKE ?");
		sql.addParameter("org", condition + "%" );
		return SqlSessionManager.getDataTable(sql);
	}
}
